<script setup>
import { useUserStore } from '@/stores'
import { ref } from 'vue'
const {
  user: { username, nickname, email, id }
} = useUserStore()
import { userInfoService, updateUserInfo } from '@/api/user'
const formUser = ref({ username, nickname, email, id })
const getUserInfo = async () => {
  const res = await userInfoService()
  formUser.value = res.data.data
  formUser.value.id = res.data.data.id
  console.log(formUser.value)
}
const formRef = ref()
const rules = {
  nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    {
      pattern: /^\S{2,10}$/,
      message: '昵称必须是2-10位的非空字符串',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入用户邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ]
}
getUserInfo()
const onSubmit = async () => {
  const valid = await formRef.value.validate()
  if (valid) {
    await updateUserInfo(formUser.value)
    ElMessage({
      message: '修改成功',
      type: 'success'
    })
    getUserInfo()
  }
}
</script>
<template>
  <div>
    基本资料

    <el-form
      ref="formRef"
      :rules="rules"
      :inline="true"
      :model="formUser"
      class="demo-form-inline"
    >
      <el-form-item label="用户名">
        <el-input
          v-model="formUser.username"
          :placeholder="formUser.username"
          clearable
          disabled
        />
      </el-form-item>

      <el-form-item prop="nickname" label="昵称">
        <el-input v-model="formUser.nickname" clearable />
      </el-form-item>

      <el-form-item prop="email" label="邮箱">
        <el-input
          v-model="formUser.email"
          :placeholder="formUser.email"
          clearable
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style lang="scss" scoped></style>
